package com.xzzz.irda.auth.core;

import com.xzzz.irda.auth.core.exception.AuthFailureHandler;
import com.xzzz.irda.auth.core.exception.DefaultAuthFailureHandler;
import com.xzzz.irda.auth.core.token.AuthorizationRepository;
import com.xzzz.irda.auth.core.token.DefaultAuthorizationRepositoryRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 基础配置信息
 *
 * 授权存储方式
 * @see AuthorizationRepository
 * 过滤器异常处理
 * @see AuthFailureHandler
 * Redis 对象,用于注入到其他手工 new 的类中
 * @see StringRedisTemplate
 *
 * @author wangyf
 * 
 */
public class AuthBaseConfiguration implements AuthConfig {

    /**
     * 授权信息的存储方式
     *
     * 默认: {@link DefaultAuthorizationRepositoryRedis}
     */
    private volatile AuthorizationRepository authorizationRepository;

    /**
     * filter 中的异常处理方式
     *
     * 默认: {@link DefaultAuthFailureHandler}
     */
    private volatile AuthFailureHandler authFailureHandler;

    /**
     * RedisTemplate
     * 用来注入到某些其他对象中
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    // ------------------------------< 授权存储 >------------------------------

    @Autowired(required = false)
    public void setAuthorizationRepository(AuthorizationRepository authorizationRepository) {
        this.authorizationRepository = authorizationRepository;
    }

    /**
     * 获取授权信息的存储方式
     * 若未注入则登录或鉴权时初始化,可能存在多线程创建覆盖,双检索单例
     * @return 授权存储方式
     */
    public AuthorizationRepository getAuthorizationRepository() {
        if (this.authorizationRepository == null) {
            synchronized (DefaultAuthorizationRepositoryRedis.class) {
                if (this.authorizationRepository == null) {
                    this.authorizationRepository = new DefaultAuthorizationRepositoryRedis(stringRedisTemplate);
                }
            }
        }
        return authorizationRepository;
    }


    // ------------------------------< 异常处理 >------------------------------

    @Autowired(required = false)
    public void setAuthFailureHandler(AuthFailureHandler authFailureHandler) {
        this.authFailureHandler = authFailureHandler;
    }

    /**
     * 授权异常处理
     * 若未注入则登录或鉴权时初始化,可能存在多线程创建覆盖,双检索单例
     * @return 异常处理
     */
    public AuthFailureHandler getAuthFailureHandler() {
        if (this.authFailureHandler == null) {
            synchronized (DefaultAuthFailureHandler.class) {
                if (this.authFailureHandler == null) {
                    this.authFailureHandler = new DefaultAuthFailureHandler();
                }
            }
        }
        return authFailureHandler;
    }
}
